package com.hsmw.api.controller.pub;

import com.alibaba.fastjson.JSONObject;
import com.hsmw.api.service.HsmwGpsService;
import com.hsmw.api.service.HttpClientUtil;
import com.hsmw.api.vo.WXPushVO;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.constant.PushOrderStatusEnum;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.HsmwGps;
import com.hsmw.domain.HsmwUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service//将这个对象加入Spring容器中
public class WeapPushUtils {

    private static HashMap tokenHub =new HashMap<>();

    public static DataResponse pushForemanMsg(WXPushVO wxPushVO,HsmwGpsService hsmwGpsService){
        String accessToken = getForemanAccessToken();
        JSONObject sendParam = new  JSONObject();
        sendParam.put("template_id",CommonConstants.WX_FOREMEN_TEMP_ID);
        sendParam.put("touser",wxPushVO.getOpenId());

        JSONObject mpTemplateMsg = new JSONObject();
        mpTemplateMsg.put("appid",CommonConstants.WX_PUBLIC_APP_ID);
        mpTemplateMsg.put("template_id",CommonConstants.WX_FOREMEN_TEMP_ID);
        mpTemplateMsg.put("url",CommonConstants.WX_DOWN_URL);

        JSONObject miniprogram = new JSONObject();
        miniprogram.put("appid",CommonConstants.WX_FOREMAN_APPID);
        //miniprogram.put("pagepath","index?foo=bar");
        mpTemplateMsg.put("miniprogram",miniprogram);

        JSONObject params =new JSONObject();

        JSONObject first =new JSONObject();
        first.put("value",wxPushVO.getMainTitle());
        first.put("color","#173177");
        params.put("first",first);

        JSONObject keyword1 =new JSONObject();
        keyword1.put("value",wxPushVO.getOrderId());
        keyword1.put("color","#173177");
        params.put("keyword1",keyword1);

        JSONObject keyword2 =new JSONObject();
        keyword2.put("value","基地");
        keyword2.put("color","#173177");
        params.put("keyword2",keyword2);

        JSONObject keyword3 =new JSONObject();
        keyword3.put("value",wxPushVO.getConstructionAddress());
        keyword3.put("color","#173177");
        params.put("keyword3",keyword3);



        JSONObject keyword4 =new JSONObject();
        keyword4.put("value",wxPushVO.getVehicleNums());
        keyword4.put("color","#173177");
        params.put("keyword4",keyword4);

        JSONObject keyword5 =new JSONObject();
        keyword5.put("value","18***********");
        keyword5.put("color","#173177");
        params.put("keyword5",keyword5);

        JSONObject remark =new JSONObject();
        remark.put("value",wxPushVO.getConstructionPosition());
        remark.put("color","#173177");
        params.put("remark",remark);

        mpTemplateMsg.put("data",params);

        sendParam.put("mp_template_msg", mpTemplateMsg);
        try {
            String url = CommonConstants.WX_PUBLIC_URL + "?access_token=" + accessToken;
            String result = HttpClientUtil.HttpPostWithJson(url, sendParam.toJSONString());
            System.out.println("工长推送进行统计 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++result=====" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            HsmwGps gps = new HsmwGps();
            gps.setImeiNum(wxPushVO.getReportName());
            gps.setVehicleId(wxPushVO.getMainTitle());
            gps.setVehicleId("accessToken=="+accessToken);
            gps.setMobileLocate("工长推送：openid："+wxPushVO.getOpenId()+"result="+result);
            hsmwGpsService.save(gps);
            String errorCode = jsonObject.getString("errcode");
            String errormsg = jsonObject.getString("errcode");
            return DataResponse.success(CommonConstants.ResponseStatus.SUCCESS);
        } catch (Exception e) {
            return DataResponse.failure(CommonConstants.ResponseStatus.FAIL);
        }
    }


    public static DataResponse pushPMProcessMsg(WXPushVO wxPushVO){
        String accessToken = getPmAccessToken();
        JSONObject sendParam = new  JSONObject();
        sendParam.put("template_id",CommonConstants.WX_PM_PROCESS_TEMP_ID);
        sendParam.put("touser",wxPushVO.getOpenId());

        JSONObject mpTemplateMsg = new JSONObject();
        mpTemplateMsg.put("appid",CommonConstants.WX_PUBLIC_APP_ID);
        mpTemplateMsg.put("template_id",CommonConstants.WX_PM_PROCESS_TEMP_ID);
        mpTemplateMsg.put("url",CommonConstants.WX_DOWN_URL);

        JSONObject miniprogram = new JSONObject();
        miniprogram.put("appid",CommonConstants.WX_PM_APPID);
        //miniprogram.put("pagepath","index?foo=bar");
        mpTemplateMsg.put("miniprogram",miniprogram);

        JSONObject params =new JSONObject();
/*

        JSONObject first =new JSONObject();
        first.put("value",wxPushVO.getMainTitle());
        first.put("color","#173177");
        params.put("first",first);
*/

        JSONObject keyword1 =new JSONObject();
        keyword1.put("value",wxPushVO.getItemName());
        keyword1.put("color","#173177");
        params.put("keyword1",keyword1);

        JSONObject keyword2 =new JSONObject();
        keyword2.put("value","已完成方量："+wxPushVO.getAlreadyVolume()+",进度"+wxPushVO.getProcessStatus());
        keyword2.put("color","#173177");
        params.put("keyword2",keyword2);

        JSONObject keyword3 =new JSONObject();
        keyword3.put("value",wxPushVO.getReportName());
        keyword3.put("color","#173177");
        params.put("keyword3",keyword3);

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        LocalDateTime startWorkTime = wxPushVO.getStartWorkTime();
        JSONObject keyword4 =new JSONObject();
        keyword4.put("value", "施工开始时间："+startWorkTime.format(dtf)+"目前项目进展正常"+"如有任何问题请致电相应的工长！");
        keyword4.put("color","#173177");
        params.put("keyword4",keyword4);

        JSONObject remark =new JSONObject();
        remark.put("value","如需查看详情，请点击下方小程序！");
        remark.put("color","#173177");
        params.put("remark",remark);

        mpTemplateMsg.put("data",params);

        sendParam.put("mp_template_msg", mpTemplateMsg);
        try {
            String url = CommonConstants.WX_PUBLIC_URL + "?access_token=" + accessToken;
            String result = HttpClientUtil.HttpPostWithJson(url, sendParam.toJSONString());
            System.out.println("result=====" + result);

            JSONObject jsonObject = JSONObject.parseObject(result);
            String errorCode = jsonObject.getString("errcode");
            String errormsg = jsonObject.getString("errcode");
            return DataResponse.success(CommonConstants.ResponseStatus.SUCCESS);
        } catch (Exception e) {
            return DataResponse.failure(CommonConstants.ResponseStatus.FAIL);
        }
    }

    public static DataResponse pushPMSuccMsg(WXPushVO wxPushVO){
        String accessToken = getPmAccessToken();
        JSONObject sendParam = new  JSONObject();
        sendParam.put("template_id",CommonConstants.WX_TEMPLATE_ID);
        sendParam.put("touser",wxPushVO.getOpenId());

        JSONObject mpTemplateMsg = new JSONObject();
        mpTemplateMsg.put("appid",CommonConstants.WX_PUBLIC_APP_ID);
        mpTemplateMsg.put("template_id",CommonConstants.WX_PM_TEMP_ID);
        mpTemplateMsg.put("url",CommonConstants.WX_DOWN_URL);

        JSONObject miniprogram = new JSONObject();
        miniprogram.put("appid",CommonConstants.WX_PM_APPID);
        //miniprogram.put("pagepath","index?foo=bar");
        mpTemplateMsg.put("miniprogram",miniprogram);

        JSONObject params =new JSONObject();

      /*  JSONObject first =new JSONObject();
        first.put("value",wxPushVO.getMainTitle());
        first.put("color","#173177");
        params.put("first",first);*/

        JSONObject keyword1 =new JSONObject();
        keyword1.put("value",wxPushVO.getReportName());
        keyword1.put("color","#173177");
        params.put("keyword1",keyword1);

        JSONObject keyword2 =new JSONObject();
        keyword2.put("value","###");
        keyword2.put("color","#173177");
        params.put("keyword2",keyword2);

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        JSONObject keyword3 =new JSONObject();
        keyword3.put("value",wxPushVO.getStartTime().format(dtf) +"- "+wxPushVO.getEndTime().format(dtf));
        keyword3.put("color","#173177");
        params.put("keyword3",keyword3);
        JSONObject remark =new JSONObject();
        remark.put("value","如需查看详情，请点击下方小程序！");
        remark.put("color","#173177");
        params.put("remark",remark);

        mpTemplateMsg.put("data",params);

        sendParam.put("mp_template_msg", mpTemplateMsg);
        try {
            String url = CommonConstants.WX_PUBLIC_URL + "?access_token=" + accessToken;
            String result = HttpClientUtil.HttpPostWithJson(url, sendParam.toJSONString());
            System.out.println("result=====" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String errorCode = jsonObject.getString("errcode");
            String errormsg = jsonObject.getString("errcode");
            return DataResponse.success(CommonConstants.ResponseStatus.SUCCESS);
        } catch (Exception e) {
            return DataResponse.failure(CommonConstants.ResponseStatus.FAIL);
        }
    }


    public static   String  getAccessToken(){
        if(tokenHub.size()==0){
           String token  =generateToken();
            tokenHub.put("createTime",new Date());
            tokenHub.put("token",token);
            return token;
        }else{
            Date createTime = (Date)tokenHub.get("createTime");
            Long now  = System.currentTimeMillis();
            if(now - createTime.getTime() >= 7200000){
                //如果创建时间大于7200s 则过期了，需要重新生成
                String newToken = generateToken();
                tokenHub.put("createTime",new Date());
                tokenHub.put("token",newToken);
                return  newToken;
            }else{
                return  (String) tokenHub.get("token");
            }
        }
    }
    public  static String  generateToken(){
        String url = CommonConstants.WX_ACCESS_URL+"?grant_type=client_credential&appid=wx14e73b25654f2308&secret=87ee49cc145db259320b69d037a60b7a";
        String res="";
        HashMap param = new HashMap();
        try{
            res = HttpClientUtil.doGet(url,param);
        }catch (Exception e){
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(res);
        String  accessToken = jsonObject.getString("access_token");

        return  accessToken;
    }

    public static   String  getForemanAccessToken(){
        if(tokenHub.size()==0 || StringUtils.isNull(tokenHub.get("foreToken"))){
            String token  =generateForemanToken();
            tokenHub.put("createForeTime",new Date());
            tokenHub.put("foreToken",token);
            return token;
        }else{
            Date createTime = (Date)tokenHub.get("createForeTime");
            Long now  = System.currentTimeMillis();
            if(now - createTime.getTime() >= 5000000){
                //如果创建时间大于7200s 则过期了，需要重新生成
                String newToken = generateForemanToken();
                tokenHub.put("createForeTime",new Date());
                tokenHub.put("foreToken",newToken);
                return  newToken;
            }else{
                return  (String) tokenHub.get("foreToken");
            }
        }
    }
    public  static String  generateForemanToken(){
        String url = CommonConstants.WX_ACCESS_URL+"?grant_type=client_credential&appid="+CommonConstants.WX_FOREMAN_APPID+"&secret="+CommonConstants.WX_FOREMAN_APP_SECRET;
        String res="";
        HashMap param = new HashMap();
        try{
            res = HttpClientUtil.doGet(url,param);
        }catch (Exception e){
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(res);
        String  accessToken = jsonObject.getString("access_token");

        return  accessToken;
    }



    public static   String  getPmAccessToken(){
        if(tokenHub.size()==0 || StringUtils.isNull(tokenHub.get("PMToken"))){
            String token  =generatePmToken();
            tokenHub.put("createPMTime",new Date());
            tokenHub.put("PMToken",token);
            return token;
        }else{
            Date createTime = (Date)tokenHub.get("createPMTime");
            Long now  = System.currentTimeMillis();
            if(now - createTime.getTime() >= 5000000){
                //如果创建时间大于7200s 则过期了，需要重新生成
                String newToken = generatePmToken();
                tokenHub.put("createPMTime",new Date());
                tokenHub.put("PMToken",newToken);
                return  newToken;
            }else{
                return  (String) tokenHub.get("PMToken");
            }
        }
    }
    public  static String  generatePmToken(){
        String url = CommonConstants.WX_ACCESS_URL+"?grant_type=client_credential&appid="+CommonConstants.WX_PM_APPID+"&secret="+CommonConstants.WX_PM_APP_SECRET;
        String res="";
        HashMap param = new HashMap();
        try{
            res = HttpClientUtil.doGet(url,param);
        }catch (Exception e){
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(res);
        String  accessToken = jsonObject.getString("access_token");

        return  accessToken;
    }


    public static String getFileNameFromUrl(String url){
        String name = new Long(System.currentTimeMillis()).toString() + ".X";
        int index = url.lastIndexOf("/");
        if(index > 0){
            name = url.substring(index + 1);
            if(name.trim().length()>0){
                return name;
            }
        }
        return name;
    }
    public static void main(String[] args) {
        for(int i=0;i<10;i++){
            HsmwUser user  =new HsmwUser();
            user.setOpenId("ojfQI5tj-74vom129qNmZ-o-2YRc");
            String token =getAccessToken();
            //pushServiceMsg("od3L15Ig6KIwjz4OqtMHfHiojFi0",new WXPushVO());
            //推送 工长信息变化
            WXPushVO vo = new WXPushVO();
            ///vo.setMainTitle("施工进度更新提醒！");
            vo.setOrderId("HOVO1623132182cc9deb53e97f");
            vo.setConstructionAddress("天津市天津市滨海新区和旭路与和畅路交叉口东");
            vo.setVehicleNums("津M99996,津M9999&");
            vo.setProcessStatus("较慢");
            vo.setStartWorkTime(LocalDateTime.now());
            vo.setOpenId("ojfQI5tj-74vom129qNmZ-o-2YRc");
            vo.setTemplateId(CommonConstants.WX_FOREMEN_TEMP_ID);

            vo.setAlreadyVolume("120");
            vo.setItemName("sdfjsidfsf");
            vo.setReportName("ZHANGSANN");
            vo.setStartTime(LocalDate.now());
            vo.setEndTime(LocalDate.now());
            vo.setReportName("zhangsan ");
            pushForemanMsgs(vo);

            String mainTitle = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
            System.out.println(mainTitle);

            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            LocalDateTime startWorkTime =LocalDateTime.now();
            System.out.println(startWorkTime.format(dtf));
        }

    }

    public static DataResponse pushForemanMsgs(WXPushVO wxPushVO){
        String accessToken = getForemanAccessToken();
        JSONObject sendParam = new  JSONObject();
        sendParam.put("template_id",CommonConstants.WX_FOREMEN_TEMP_ID);
        sendParam.put("touser",wxPushVO.getOpenId());

        JSONObject mpTemplateMsg = new JSONObject();
        mpTemplateMsg.put("appid",CommonConstants.WX_PUBLIC_APP_ID);
        mpTemplateMsg.put("template_id",CommonConstants.WX_FOREMEN_TEMP_ID);
        mpTemplateMsg.put("url",CommonConstants.WX_DOWN_URL);

        JSONObject miniprogram = new JSONObject();
        miniprogram.put("appid",CommonConstants.WX_FOREMAN_APPID);
        //miniprogram.put("pagepath","index?foo=bar");
        mpTemplateMsg.put("miniprogram",miniprogram);

        JSONObject params =new JSONObject();

        JSONObject first =new JSONObject();
        first.put("value",wxPushVO.getMainTitle());
        first.put("color","#173177");
        params.put("first",first);

        JSONObject keyword1 =new JSONObject();
        keyword1.put("value",wxPushVO.getOrderId());
        keyword1.put("color","#173177");
        params.put("keyword1",keyword1);

        JSONObject keyword2 =new JSONObject();
        keyword2.put("value","基地");
        keyword2.put("color","#173177");
        params.put("keyword2",keyword2);

        JSONObject keyword3 =new JSONObject();
        keyword3.put("value",wxPushVO.getConstructionAddress());
        keyword3.put("color","#173177");
        params.put("keyword3",keyword3);



        JSONObject keyword4 =new JSONObject();
        keyword4.put("value",wxPushVO.getVehicleNums());
        keyword4.put("color","#173177");
        params.put("keyword4",keyword4);

        JSONObject keyword5 =new JSONObject();
        keyword5.put("value","18***********");
        keyword5.put("color","#173177");
        params.put("keyword5",keyword5);

        JSONObject remark =new JSONObject();
        remark.put("value",wxPushVO.getConstructionPosition());
        remark.put("color","#173177");
        params.put("remark",remark);

        mpTemplateMsg.put("data",params);

        sendParam.put("mp_template_msg", mpTemplateMsg);
        try {
            String url = CommonConstants.WX_PUBLIC_URL + "?access_token=" + accessToken;
            String result = HttpClientUtil.HttpPostWithJson(url, sendParam.toJSONString());
            System.out.println("工长推送进行统计 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++result=====" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String errorCode = jsonObject.getString("errcode");
            String errormsg = jsonObject.getString("errcode");
            return DataResponse.success(CommonConstants.ResponseStatus.SUCCESS);
        } catch (Exception e) {
            return DataResponse.failure(CommonConstants.ResponseStatus.FAIL);
        }
    }

}
